﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace ExhibitionDraw.Common
{
    public class DPaint : Shape
    {
        private Canvas parent;//父类的Canvas
        bool isRectStart = true;
        bool isPolygonStart = true;
        bool isMove = false;//记录是否移动
        Rectangle rg;
        Point startPoint;//记录鼠标移动的起始点
        private PointCollection Points = new PointCollection();//记录图形需要的点     
        double x = 0.0;
        double y = 0.0;
        public event EventHandler<DrawEventArgs> DrawEndDrawed;
        public event EventHandler<DrawEventArgs> PointDrawed;
        public int dtp = 0;
        public DPaint()
        {
            //  parent = cas; 
          
            this.Loaded += new RoutedEventHandler(DRectangleLoad);
        }

        private void DRectangleLoad(object sender, RoutedEventArgs e)
        {
            try
            {
                parent = this.Parent as Canvas;

            }
            catch (Exception)
            {
                throw new Exception("DRectangle 的父元素应该指定为Canvas类型！");
            }
 
                parent.MouseLeftButtonDown += new MouseButtonEventHandler(parent_MouseLeftButtonDown);
                parent.MouseMove += new MouseEventHandler(parent_MouseMove);
                parent.MouseLeftButtonUp += new MouseButtonEventHandler(parent_MouseLeftButtonUp);
            
        }

        public void DrawPolyon() { 
            
        }

        public  void DrawRectangle() {
                
        }

        #region 不规则图形
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void parent_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (dtp == 1) {
                Rectangle item = sender as Rectangle;
                DrawEventArgs args = new DrawEventArgs();
                isPolygonStart = true;

                if (DrawEndDrawed != null)
                {
                    args.Points = GetPoints();
                    DrawEndDrawed(sender, args);
                }
            }
        }

        private void parent_MouseMove(object sender, MouseEventArgs e)
        {
            if (dtp == 1)
            {
                LastPoint = e.GetPosition(parent);
                if (CheckCompleted())
                {
                    parent.Cursor = Cursors.Hand; 
                }
                else
                {
                    parent.Cursor = Cursors.Arrow;
                }
            }
            else {
                if (isMove)
                {
                    if (!isRectStart)
                    {
                        rg.Width = Math.Abs(e.GetPosition(parent).X - startPoint.X);
                        rg.Height = Math.Abs(e.GetPosition(parent).Y - startPoint.Y);
                    }
                    Points.Clear();
                    Points.Add(startPoint);

                }
            }
        }

        private void parent_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            #region  初始化不规则图形
            if (dtp == 2)
            {
                if (isRectStart)
                {
                    rg = new Rectangle()
                    {
                        Fill = new SolidColorBrush(Colors.Red),
                        Name = Guid.NewGuid().ToString(),
                        RadiusX = 5,
                        RadiusY = 5,
                        AllowDrop = true,

                    };



                    rg.MouseMove += new MouseEventHandler(rg_Move);
                    rg.MouseLeftButtonDown += new MouseButtonEventHandler(rg_MouseLeftButtonDown);
                    rg.MouseLeftButtonUp += new MouseButtonEventHandler(rg_MouseLeftButtonUp);
                    CreatMenu(rg);

                    startPoint = e.GetPosition(parent);
                    Points = new PointCollection();
                    Points.Add(startPoint);
                    rg.SetValue(Canvas.LeftProperty, startPoint.X);
                    rg.SetValue(Canvas.TopProperty, startPoint.Y);
                    parent.Children.Add(rg);
                    isRectStart = false;
                    isMove = true;

                }
            }
            else
            {
                if (isPolygonStart)
                {
                    Polygon _polyline = new Polygon();
                    _polyline.Fill = this.Fill == null ? new SolidColorBrush(Color.FromArgb(0x88, 0xff, 0xff, 0x00)) : this.Fill;
                    _polyline.Stroke = this.Stroke == null ? new SolidColorBrush(Colors.Black) : this.Stroke;
                    _polyline.StrokeThickness = _polyline.StrokeThickness < 1 ? 1.0 : _polyline.StrokeThickness;
                    _polyline.Points = this.Points;
                    _polyline.MouseLeftButtonDown += new MouseButtonEventHandler(polyline_MouseLeftButtonDown);
                    _polyline.MouseLeftButtonUp += new MouseButtonEventHandler(polyline_MouseLeftButtonUp);
                    _polyline.MouseMove += new MouseEventHandler(polyline_MouseMove);
                    parent.Children.Add(_polyline);

                    isPolygonStart = false;
                }



            #endregion
                DrawEventArgs args = new DrawEventArgs();
                if (!CheckCompleted())
                {
                   
                    if (Points.Count == 0)
                    {

                        Points.Add(e.GetPosition(parent));

                        args.CurrentPoint = Points[0];
                        if (PointDrawed != null)
                        {
                            DrawJoinPoint(args.CurrentPoint, Colors.Red, Colors.Black, 5, 1);
                        }
                        //PointDrawed(sender, args);
                    }
                    else
                    {
                        Points[Points.Count - 1] = LastPoint;


                        args.CurrentPoint = LastPoint;
                        if (PointDrawed != null)
                        {
                            DrawJoinPoint(args.CurrentPoint, Colors.Red, Colors.Black, 5, 1);
                        }


                    }
                    Points.Add(e.GetPosition(parent));

                }
                else {
                   
                        LastPoint = Points[0];
                        isPolygonStart = true;
                        if (DrawEndDrawed != null)
                        {
                            args.Points = GetPoints();
                            DrawEndDrawed(sender, args);
                        }
                        Points = new PointCollection();
                        Points.Add(e.GetPosition(parent));
                        return; 
                }
            }
        }



        #region 创建右键菜单
        private void CreatMenu(Rectangle rgc)
        {
            ContextMenu cm = new ContextMenu();
            MenuItem m1 = new MenuItem();
            m1.Header = "复制";
            m1.Click += new RoutedEventHandler(Copy_Click);
            cm.Items.Add(m1);

            MenuItem m2 = new MenuItem();
            m2.Header = "修改";
            m2.Click += new RoutedEventHandler(Modify_Click);
            cm.Items.Add(m2);

            ContextMenuService.SetContextMenu(rgc, cm);
        }

        /// <summary>
        /// 在图片上点击修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Modify_Click(object sender, RoutedEventArgs e)
        {


        }

        private void Copy_Click(object sender, RoutedEventArgs e)
        {
            Rectangle rect = new Rectangle();
            rect.Name = new Guid().ToString();
            rect.SetValue(Canvas.LeftProperty, Convert.ToDouble(rg.GetValue(Canvas.LeftProperty)) * 2 + 10);
            rect.SetValue(Canvas.TopProperty, Convert.ToDouble(rg.GetValue(Canvas.TopProperty)) * 2 + 10);
            rect.Width = rg.Width;
            rect.Height = rg.Height;
            rect.Fill = rg.Fill;
            rect.RadiusX = 10;
            rect.RadiusY = 10;
            rect.MouseMove += new MouseEventHandler(rg_Move);
            rect.MouseLeftButtonDown += new MouseButtonEventHandler(rg_MouseLeftButtonDown);
            rect.MouseLeftButtonUp += new MouseButtonEventHandler(rg_MouseLeftButtonUp);
            CreatMenu(rect);
            parent.Children.Add(rect);
        }
        #endregion
        private void DrawJoinPoint(Point p, Color fill, Color stoke, double radio, double lineThickness)
        {


            Ellipse e = new Ellipse();
            e.Fill = new SolidColorBrush(fill);
            e.Stroke = new SolidColorBrush(stoke);
            e.Height = e.Width = radio + lineThickness;
            e.StrokeThickness = lineThickness;

            e.SetValue(Canvas.LeftProperty, p.X - e.Width / 2);
            e.SetValue(Canvas.TopProperty, p.Y - e.Height / 2);

            parent.Children.Add(e);
            //if (!IsCompleted)
            //{
            //    Points.Add(e);
            //}
        }

        private bool CheckCompleted()
        {
            return Points.Count > 0 && Math.Abs(Points[0].X - LastPoint.X) < 5 && Math.Abs(Points[0].Y - LastPoint.Y) < 5;
        }

        private static DependencyProperty LastPointProperty = DependencyProperty.Register(
            "LastPoint", typeof(Point), typeof(DPaint),
            new PropertyMetadata(new PropertyChangedCallback(LastPointChanged)));

        public Point LastPoint
        {
            get { return (Point)GetValue(LastPointProperty); }
            set { SetValue(LastPointProperty, value); }
        }

        public static void LastPointChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            //DPolygon poly = sender as DPolygon;
            //if (!poly.IsCompleted && poly.Points.Count > 0)
            //{
            //    poly.Points[poly.Points.Count - 1] = (Point)e.NewValue;
            //}
        }

        private void polyline_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
             
        }

        private void polyline_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            
        }

        private void polyline_MouseMove(object sender, MouseEventArgs e)
        {
             
        }
        #endregion

        #region 规则画图的鼠标操作
  

        /// <summary>
        /// 矩形鼠标弹起
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rg_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {

            Rectangle item = sender as Rectangle;
            DrawEventArgs args = new DrawEventArgs();
            isRectStart = true;
            item.ReleaseMouseCapture();
            if (DrawEndDrawed != null)
            {
                args.Points = GetPoints();
                DrawEndDrawed(sender, args);
            }
        }
        /// <summary>
        /// 矩形鼠标按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //e.Handled = true;
            Rectangle item = sender as Rectangle;
            y = e.GetPosition(null).Y;
            x = e.GetPosition(null).X;
            //isMove = true;
            item.CaptureMouse();
            isRectStart = true;
            item.Stroke = new SolidColorBrush(Colors.Black);
            item.StrokeThickness = 3;

        }
        /// <summary>
        /// 矩形鼠标移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rg_Move(object sender, MouseEventArgs e)
        {
            Rectangle item = sender as Rectangle;

            if (isMove)
            {
                // Calculate the current position of the object. 
                double deltaV = e.GetPosition(null).Y - y;
                double deltaH = e.GetPosition(null).X - x;
                double newTop = deltaV + (double)item.GetValue(Canvas.TopProperty);
                double newLeft = deltaH + (double)item.GetValue(Canvas.LeftProperty);
                // Set new position of object. 
                item.SetValue(Canvas.TopProperty, newTop);
                item.SetValue(Canvas.LeftProperty, newLeft);
                // Update position global variables.  
                y = e.GetPosition(null).Y;
                x = e.GetPosition(null).X;
                isRectStart = true;
                Points.Add(e.GetPosition(null));
            }
        }
        #endregion


        public List<Point> GetPoints()
        {
            List<Point> points = new List<Point>(Points.Count);
            foreach (Point p in Points)
                points.Add(p);
            return points;
        }
    }
}
